package com.cnzhy.executor;

import com.cnzhy.bean.User;
import com.cnzhy.session.MyConfiguration;
import org.dom4j.DocumentException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class MyBaseExecutor implements Executor {

    private final MyConfiguration xmlConfiguration = new MyConfiguration();

    @Override
    public <T> T query(String sql, Object parameter) {
        Connection connection = getConnection();
        ResultSet set;
        PreparedStatement pre;
        User u = new User();
        try {
            pre = connection.prepareStatement(sql);
            // /设置参数
            pre.setString(1, parameter.toString());
            set = pre.executeQuery();
            // 遍历结果集
            while (set.next()) {
                u.setId(set.getString(1));
                u.setUsername(set.getString(2));
                u.setPassword(set.getString(3));
            }
        } catch (Exception ignored) {

        }
        return (T) u;
    }

    private Connection getConnection() {
        Connection connection = null;
        try {
            connection = xmlConfiguration.build("config.xml");
        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }

}
